<template>
  <div>
    <!-- 登陆拦截判断 -->
    <!-- <el-dialog
        :visible="isShowDialog"
        title="请先选择角色"
        width="60%"
        @close="handleClose"
        left>
        <div class="wrapScroll">
            <p  style=""
            v-for="(item,index) of selectionRole"
            :key="index"
            @click="setUserRoleHandle(item)">
                <router-link class="dialogP" to="">
                
                公司：{{item.dealerName}}&nbsp;&nbsp;&nbsp;&nbsp;--
                部门：{{item.orgName}}&nbsp;&nbsp;&nbsp;&nbsp;--
                角色：{{item.roleName}}
                </router-link>
            </p>
        </div>
    </el-dialog>-->
    <!-- 角色切换 -->
    <BaseDialog :visible.sync="isShowDialog" title="请您先选择职位" destroyOnClose>
      <div class="wrapScroll">
        <div
          class="dialogP"
          style
          v-for="(item,index) of selectionRole"
          :key="index"
          @click="setUserRoleHandle(item)"
        >
          <router-link to="./">
            <!-- 公司：{{item.dealerName}}&nbsp;&nbsp;&nbsp;&nbsp;-- -->
            <h3>{{item.orgName}}</h3>
            <!-- &nbsp;&nbsp;&nbsp;&nbsp;-- -->
            <p>{{item.roleName}}</p>
          </router-link>
        </div>
        <div style="text-align: center;margin-top: 30px;">
          <el-button @click="handleClose">返回</el-button>
          <!-- <el-button  type="primary">确定</el-button> -->
        </div>
      </div>
    </BaseDialog>
    <a href="/updateWXOpenId" v-show="false" ref="reg"></a>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/login/types';
import { sleep } from '@/utils';
import { setToken, setDataType, setAppId, jsEncrypt } from '@/assets/js/auth';
import { weChatCallback, doLogin, initLogin, getUserInfo, sendPhoneCode, roleDetail, setUserRole } from '@/api/login/index';
export default {
  name: 'getAccessToken',
  data() {
    return {
      loginForm: {
        openid: '',
        loginType: '',
        appId: ''
      },
      selectionRole: [],
      isShowDialog: false,
      openid: ''
    };
  },
  mounted() {
    this.geCodeAndState();
  },
  methods: {
    geCodeAndState() {
      if (this.$route.query) {
        let params = {
          appId: localStorage.getItem('appId') ? localStorage.getItem('appId') : 'cyx', //后期根据各自厂端自己处理
          code: this.$route.query.code,
          state: this.$route.query.state
        };
        weChatCallback(params).then(res => {
          localStorage.setItem('openidwx', res.data.openid);
          localStorage.setItem('city', res.data.wechatInfo.city);
          localStorage.setItem('country', res.data.wechatInfo.country);
          localStorage.setItem('headimgurl', res.data.wechatInfo.headimgurl);
          localStorage.setItem('nickname', res.data.wechatInfo.nickname);
          localStorage.setItem('province', res.data.wechatInfo.province);
          localStorage.setItem('sex', res.data.wechatInfo.sex);
          localStorage.setItem('type', res.data.wechatInfo.type);
          localStorage.setItem('unionid', res.data.wechatInfo.unionid);
          if (res.data.flag == 'true') {
            this.loginForm.openid = res.data.openid;
            this.loginForm.loginType = res.data.loginType;
            this.loginForm.appId = localStorage.getItem('appId');
            this.handleLogin();
          } else {
            this.$refs.reg.click();
          }
        });
      } else {
        next();
      }
    },
    ...mapActions('app', ['createLoginInfo']),
    async handleLogin() {
      const res = await doLogin({
        appId: this.loginForm.appId ? this.loginForm.appId : 'cyx',
        openId: this.loginForm.openid,
        loginType: this.loginForm.loginType
      });
      console.log(res, 'res');
      if (res.resultCode === 200) {
        setToken(res.data.jwt);
        setDataType(res.data.rData.dataType);
        // 登录成功后判断角色
        // if(this.isShowDialog){
        this.selectionRole = [];
        roleDetail()
          .then(res => {
            res.data.forEach(x => {
              this.selectionRole.push(x);
            });
            if (this.selectionRole.length == 1) {
              this.isShowDialog = false;
              this.setUserRoleHandle(this.selectionRole[0]);
            } else {
              this.isShowDialog = true;
            }
          })
          .catch(err => {});
        // }
      } else if (res.resultCode === 998) {
        // this.isCodeImg=true
        console.log(
          res.errMsg
            .split(',')[1]
            .split(':')[1]
            .split('"')[1]
        );
        let base64Img = res.errMsg
          .split(',')[1]
          .split(':')[1]
          .split('"')[1];
      }
    },

    //保存角色
    setUserRoleHandle(data) {
      localStorage.setItem('roleType', data.roleType);
      setUserRole(data).then(res => {
        if (res.resultCode == 200) {
          this.initUserInfo();
        }
      });
    },
    // 获取用户信息
    async initUserInfo() {
      await initLogin();
      const {
        data: { userInfo }
      } = await getUserInfo();
      this.createLoginInfo({
        id: userInfo.userId,
        name: userInfo.userName
      });
      const userAppId = await getUserInfo();
      if (userAppId.resultCode == 200) {
        setAppId(userAppId.data.userInfo.appId);
        localStorage.setItem('appId', userAppId.data.userInfo.appId);
      }
      await sleep(100);
      this.$router.push({ path: '/' });
    },
    // 关闭
    handleClose() {
      this.isShowDialog = false;
      this.checks = false;
      setToken();
      setDataType();
      sleep(0);
    }
  }
};
</script>

<style lang="less" scoped>
/* .dialogP{
  font-size: 17px;
  line-height: 50px;
  padding-left: 10px;
  display: inline-block;
}
.dialogP:hover{
  background: #5FB2F9;
} */
.wrapScroll {
  max-height: 300px;
  overflow-y: scroll;
}
.dialogP {
  font-size: 17px;
  line-height: 50px;
  padding-left: 10px;
  a {
    display: block;
    h3 {
      color: #666;
      font-weight: 900;
    }
    p {
      height: 26px;
      line-height: 20px;
      font-size: 14px;
      margin-left: 10px;
    }
  }
}
.dialogP:hover {
  border: 1px solid #1682e6;
  h3 {
    color: #1682e6;
  }
}
</style>
